<template>
  <view class="payment-edit-page">
    <!-- <view class="page-title">
      <text>编辑收款单</text>
    </view> -->
    
    <!-- 基本信息区域 -->
    <view class="info-section">
      <view class="info-item">
        <view class="info-icon"><u-icon name="account" size="20" color="#666666"></u-icon></view>
        <text class="info-label">客户</text>
        <view class="info-value" @click="selectCustomer">{{ formData.customerName || '请选择客户' }}</view>
      </view>
    </view>
    
    <!-- 收款金额部分 -->
    <view class="payment-section">
      <view class="section-title">收款方式</view>
      <view class="payment-methods">
        <view class="payment-method-item">
          <text class="payment-method-name">现金</text>
          <input type="digit" class="payment-method-input" v-model="formData.cashAmount" 
            @input="updateTotalAmount" placeholder="0.00" />
        </view>
        <view class="payment-method-item">
          <text class="payment-method-name">银行存款</text>
          <input type="digit" class="payment-method-input" v-model="formData.bankAmount" 
            @input="updateTotalAmount" placeholder="0.00" />
        </view>
        <view class="payment-method-item">
          <text class="payment-method-name">微信</text>
          <input type="digit" class="payment-method-input" v-model="formData.wechatAmount" 
            @input="updateTotalAmount" placeholder="0.00" />
        </view>
        <view class="payment-method-item">
          <text class="payment-method-name">支付宝</text>
          <input type="digit" class="payment-method-input" v-model="formData.alipayAmount" 
            @input="updateTotalAmount" placeholder="0.00" />
        </view>
      </view>
      <view class="payment-total">
        <text class="payment-total-label">总金额</text>
        <text class="payment-total-value">{{ formatAmount(formData.totalAmount) }}</text>
      </view>
    </view>
    
    <!-- 备注区域 -->
    <view class="remark-section">
      <text class="remark-label">备注 (最多输入200个字)</text>
      <textarea class="remark-input" v-model="formData.remark" placeholder="请输入备注内容" maxlength="200"></textarea>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-bar">
      <button class="cancel-btn" @click="handleCancel">取消</button>
      <button class="save-btn" @click="handleSave">保存</button>
    </view>
    
    <!-- 客户选择器 -->
    <u-picker :show="showCustomerPicker" :columns="[customerColumns]" keyName="label" @confirm="confirmCustomer"
      @cancel="showCustomerPicker = false">
    </u-picker>
  </view>
</template>

<script>
import api from '@/utils/api.js';

export default {
  data() {
    return {
      id: null,
      type: null,
      formData: {
        customerName: '',
        customerId: null,
        totalAmount: 0,
        cashAmount: '',
        bankAmount: '',
        wechatAmount: '',
        alipayAmount: '',
        remark: ''
      },
      originalData: {}, // 保存原始数据，用于检测变化
      showCustomerPicker: false,
      customerColumns: [],
      loading: false
    };
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id;
      this.type = options.type || 'receiveOrder';
      // 加载数据
      this.loadData();
      // 加载客户列表
      this.loadCustomerList();
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  methods: {
    // 加载收款单数据
    loadData() {
      uni.showLoading({ title: '加载中' });
      
      // 根据单据类型选择API
      let apiPromise;
      if (this.type === 'receiveOrder') {
        // 销售收款单
        apiPromise = api.getSalesDetail(this.id);
      } else {
        // 如果有其他类型的收款单，添加对应逻辑
        apiPromise = Promise.reject('不支持的单据类型');
      }
      
      apiPromise.then(res => {
        console.log('收款单数据:', res);
        
        if (res) {
          // 更新基本数据
          this.formData = {
            customerId: res.customerId,
            customerName: res.customerName || '',
            totalAmount: res.totalAmount || 0,
            cashAmount: res.cashAmount ? String(res.cashAmount) : '',
            bankAmount: res.bankAmount ? String(res.bankAmount) : '',
            wechatAmount: res.wechatAmount ? String(res.wechatAmount) : '',
            alipayAmount: res.alipayAmount ? String(res.alipayAmount) : '',
            remark: res.remark || ''
          };
          
          // 保存原始数据
          this.originalData = {...this.formData};
          
          // 如果有客户ID但没有客户名称，查询客户信息
          if (res.customerId && !res.customerName) {
            this.loadCustomerName(res.customerId);
          } else {
            uni.hideLoading();
          }
        } else {
          uni.hideLoading();
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('获取收款单数据失败:', err);
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      });
    },
    
    // 加载客户名称
    loadCustomerName(customerId) {
      api.getCustomer(customerId).then(customerRes => {
        console.log('客户信息:', customerRes);
        
        // 更新客户名称
        if (customerRes && customerRes.customerName) {
          this.formData.customerName = customerRes.customerName;
        }
        
        uni.hideLoading();
      }).catch(err => {
        console.error('获取客户信息失败:', err);
        uni.hideLoading();
      });
    },
    
    // 加载客户列表
    loadCustomerList() {
      api.listCustomer({ pageNum: 1, pageSize: 1000 }).then(res => {
        console.log('客户列表:', res);
        
        if (res && res.rows && Array.isArray(res.rows)) {
          this.customerColumns = res.rows.map(item => ({
            label: item.customerName || '未命名客户',
            value: item.id
          }));
        }
      }).catch(err => {
        console.error('获取客户列表失败:', err);
        uni.showToast({
          title: '获取客户列表失败',
          icon: 'none'
        });
      });
    },
    
    // 格式化金额显示
    formatAmount(amount) {
      if (amount === undefined || amount === null) return '0.00';
      return parseFloat(amount).toFixed(2);
    },
    
    // 更新总金额
    updateTotalAmount() {
      // 将输入的金额转换为数字，确保非数字值为0
      const cashAmount = parseFloat(this.formData.cashAmount) || 0;
      const bankAmount = parseFloat(this.formData.bankAmount) || 0;
      const wechatAmount = parseFloat(this.formData.wechatAmount) || 0;
      const alipayAmount = parseFloat(this.formData.alipayAmount) || 0;
      
      // 计算总金额
      this.formData.totalAmount = Number((cashAmount + bankAmount + wechatAmount + alipayAmount).toFixed(2));
    },
    
    // 选择客户
    selectCustomer() {
      if (this.customerColumns.length === 0) {
        uni.showToast({
          title: '正在加载客户列表',
          icon: 'none'
        });
        // 重新加载客户列表
        this.loadCustomerList();
        return;
      }
      this.showCustomerPicker = true;
    },
    
    // 确认客户选择
    confirmCustomer(e) {
      console.log('选择客户:', e);
      
      if (e && e.value && e.value.length > 0) {
        const selectedItem = e.value[0];
        this.formData.customerId = selectedItem.value;
        this.formData.customerName = selectedItem.label;
      }
      
      this.showCustomerPicker = false;
    },
    
    // 取消编辑
    handleCancel() {
      uni.navigateBack();
    },
    
    // 保存收款单
    handleSave() {
      // 验证数据
      if (!this.formData.customerId) {
        uni.showToast({
          title: '请选择客户',
          icon: 'none'
        });
        return;
      }
      
      if (this.formData.totalAmount <= 0) {
        uni.showToast({
          title: '收款金额必须大于0',
          icon: 'none'
        });
        return;
      }
      
      // 构建提交数据
      const postData = {
        id: this.id,
        customerId: this.formData.customerId,
        customerName: this.formData.customerName,
        totalAmount: this.formData.totalAmount,
        cashAmount: parseFloat(this.formData.cashAmount) || 0,
        bankAmount: parseFloat(this.formData.bankAmount) || 0,
        wechatAmount: parseFloat(this.formData.wechatAmount) || 0,
        alipayAmount: parseFloat(this.formData.alipayAmount) || 0,
        remark: this.formData.remark,
        type: this.type
      };
      
      console.log('提交数据:', postData);
      uni.showLoading({ title: '保存中' });
      
      // 调用更新API
      let apiPromise;
      if (this.type === 'receiveOrder') {
        // 更新销售收款单
        apiPromise = api.updateSales(postData);
      } else {
        // 如果有其他类型的收款单，添加对应逻辑
        apiPromise = Promise.reject('不支持的单据类型');
      }
      
      apiPromise.then(res => {
        uni.hideLoading();
        
        if (res && res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 返回详情页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res?.msg || '保存失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('保存收款单失败:', err);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.payment-edit-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 120rpx;
}

.page-title {
  background-color: #3ACBC1;
  padding: 30rpx;
  text-align: center;
  
  text {
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
  }
}

// 基本信息区域
.info-section {
  background-color: #ffffff;
  margin-top: 20rpx;
  
  .info-item {
    display: flex;
    align-items: center;
    padding: 25rpx 30rpx;
    
    .info-icon {
      margin-right: 15rpx;
    }
    
    .info-label {
      font-size: 28rpx;
      color: #333333;
      width: 100rpx;
    }
    
    .info-value {
      flex: 1;
      font-size: 28rpx;
      color: #666666;
      text-align: right;
    }
  }
}

// 收款方式区域
.payment-section {
  background-color: #ffffff;
  margin-top: 20rpx;
  
  .section-title {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.payment-methods {
  display: flex;
  flex-direction: column;
  padding: 10rpx 30rpx;
  
  .payment-method-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    .payment-method-name {
      font-size: 28rpx;
      color: #333333;
    }
    
    .payment-method-input {
      width: 200rpx;
      text-align: right;
      font-size: 28rpx;
      color: #666666;
      padding: 5rpx;
    }
  }
}

.payment-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .payment-total-label {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
  }
  
  .payment-total-value {
    font-size: 32rpx;
    color: #FF5252;
    font-weight: bold;
  }
}

// 备注区域
.remark-section {
  background-color: #ffffff;
  margin-top: 20rpx;
  padding: 20rpx 30rpx;
  
  .remark-label {
    font-size: 28rpx;
    color: #333333;
    margin-bottom: 15rpx;
    display: block;
  }
  
  .remark-input {
    width: 100%;
    height: 150rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 15rpx;
    font-size: 28rpx;
    color: #333333;
  }
}

// 底部操作栏
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .cancel-btn, .save-btn {
    flex: 1;
    height: 80rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    border-radius: 12rpx;
    margin: 0 10rpx;
  }
  
  .cancel-btn {
    background-color: #ffffff;
    color: #666666;
    border: 1rpx solid #e0e0e0;
  }
  
  .save-btn {
    background-color: #3ACBC1;
    color: #ffffff;
    border: none;
  }
}
</style> 